﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Xml;

namespace dk.Helper.Base.Core
{
    public class GameServer : IGameServer
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="T:System.Object"/> class.
        /// </summary>
        public GameServer()
        {
            Worlds = new List<IWorld>();
        }

        #region IGameServer Members

        /// <summary>
        /// Gets the worlds.
        /// </summary>
        public IList<IWorld> Worlds { get; private set; }

        /// <summary>
        /// Gets the worlds.
        /// </summary>
        /// <param name="address">The address.</param>
        public void Initialize(string address)
        {
            Worlds.Clear();
            var request = (HttpWebRequest) WebRequest.Create("http://www." + address + "/backend/get_servers_xml.php");
            var response = (HttpWebResponse) request.GetResponse();

            Stream responseStream = response.GetResponseStream();
            if (responseStream == null)
            {
                throw new NullReferenceException("Failed to get response stream.");
            }
            using (var input = new StreamReader(responseStream))
            {
                var doc = new XmlDocument();
                doc.Load(input);

                XmlNodeList worldUrlNodes = doc.SelectNodes("//urls/url");
                if (worldUrlNodes != null)
                    foreach (XmlNode worldUrlNode in worldUrlNodes)
                        if (worldUrlNode.Attributes != null)
                        {
                            IWorld world = new World(worldUrlNode.Attributes["id"].Value, address);
                            Worlds.Add(world);
                        }
            }
            OnInitialized(new EventArgs());
        }

        /// <summary>
        /// Occurs when game server initialize worlds.
        /// </summary>
        public event EventHandler Initialized;

        #endregion

        /// <summary>
        /// Raises the event.
        /// </summary>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void OnInitialized(EventArgs e)
        {
            if (Initialized != null) Initialized(this, e);
        }
    }
}